package cn.nc.config;

import cn.nc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)throws  Exception{
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http)throws  Exception{

        http.authorizeRequests()
                //访问该目录时拦截
                .antMatchers("/article/**","/page/user/**").authenticated()
                .antMatchers("/back/article/add","/user").authenticated()
                // 不拦截
                .antMatchers("/assets/**","/css/**").permitAll()
                .antMatchers("/**","/register").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();

        http.formLogin()
                .loginPage("/login").permitAll()
                .usernameParameter("username")
                .passwordParameter("password")
                .defaultSuccessUrl("/")
                .failureUrl("/login?error");

        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/");

        http.rememberMe()
                .rememberMeParameter("rememberme")
                .tokenValiditySeconds(200);
    }

}
